package com.opennews.openplatform.myspringbootmvccore.security

import com.opennews.openplatform.myspringbootcore.common.constant.HTTP_HEADER_AUTHORIZATION
import com.opennews.openplatform.myspringbootcore.security.AuthRequestValidator
import com.opennews.openplatform.myspringbootcore.security.MyClaims
import com.opennews.openplatform.myspringbootcore.security.ParsedToken
import jakarta.servlet.http.HttpServletRequest
import org.springframework.stereotype.Component

@Component
class RequestIdentityExtractor(
    private val authRequestValidator: AuthRequestValidator,
    private val request: HttpServletRequest,
) {
    /**
     * Gets claims from token in header.
     */
    fun getToken(): ParsedToken {
        // Gets authorization from request header.
        // The string should be like below example:
        // Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDU3ODIxNzUsImlhdCI6MTYwNTc3ODU3NSwiaWQiOiJ1c2VyLWlkIiwidXNlcm5hbWUiOiJIdWkiLCJyb2xlcyI6WyJBZG1pbiJdfQ.tKdhYNyeqOS_ITIV_F0sKT6N-NBFjxMkPyXAkzT43WQ
        val header = request.getHeader(HTTP_HEADER_AUTHORIZATION)
        val authorizationHeader = header?.trim()

        return authRequestValidator.checkAuthorizationHeader(authorizationHeader)
    }

    /**
     * Gets claims from token.
     */
    fun getClaims(): MyClaims {
        return getToken().claims!!
    }
}